﻿using UnityEngine;

public class ResourceView : MonoBehaviour
{
    float m_DeltaTime = 0.0f;
    Vector2 m_ScrollPos = Vector2.zero;
    GUIStyle m_FontStyle = new GUIStyle();
    bool m_ShowDetail = false;

    void Awake()
    {
        m_FontStyle.normal.textColor = Color.white;
        m_FontStyle.fontSize = 14;
    }
    
    void Update()
    {
        m_DeltaTime = Time.smoothDeltaTime;
    }

    void OnGUI()
    {
        var rect = new Rect(100, 0, Screen.width - 100, Screen.height);
        GUI.color = new Color(0, 0, 0, 0.5f);
        GUI.DrawTexture(rect, Texture2D.whiteTexture);
        GUI.color = Color.white;
        GUILayout.BeginArea(rect);
        {
            float msec = m_DeltaTime * 1000.0f;
            float fps = 1.0f / m_DeltaTime;
            GUILayout.Label(string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps));
            GUILayout.Label(string.Format("加载Bundle\t{0}", BundleManager.taskCount));
            GUILayout.Label(string.Format("缓存Bundle\t{0}", BundleManager.cacheCount));
            GUILayout.Label(string.Format("加载Asset\t\t{0}", AssetManager.taskCount));
            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button("显示详细信息", GUILayout.Width(100), GUILayout.Height(50)))
                {
                    m_ShowDetail = !m_ShowDetail;
                }
                if (GUILayout.Button("清理资源缓存", GUILayout.Width(100), GUILayout.Height(50)))
                {
                    System.GC.Collect();
                }
            }
            GUILayout.EndHorizontal();

            if (m_ShowDetail)
            {
                m_ScrollPos = GUILayout.BeginScrollView(m_ScrollPos);
                foreach (var task in AssetManager.taskes)
                {
                    GUILayout.Label(string.Format("{0}({1}%)", task.path, (int)(task.progress * 100)));
                    var btask = task.bundleTask.task as BundleTask;
                    DrawDependencies(btask.dependencies, string.Empty);
                }
                
                GUILayout.EndScrollView();
            }
        }
        GUILayout.EndArea();
    }

    static string TAB = "\t";
    void DrawBundle(BundleTask task, string tabs)
    {
        if (task == null)
            return;

        GUILayout.Label(string.Format("{0}{1}({2}%)", tabs, task.path, (int)(task.progress * 100)));
        DrawDependencies(task.dependencies, tabs);
    }

    void DrawDependencies(LoadTaskR[] dependencies, string tabs)
    {
        if (dependencies != null)
        {
            tabs += TAB;
            foreach (var dep in dependencies)
            {
                DrawBundle(dep.task as BundleTask, tabs);
            }
        }
    }
}
